<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j page-submit-order">
    <div class="content">
      <div class="step-box">
        <div class="left">
          <span class="img" />
          <span class="text">{{ $t('submitOrder.submitOrder') }}</span>
        </div>
        <div class="steps">
          <div class="item">
            <div class="number">
              step 01.
            </div>
            <div class="text">
              {{ $t('submitOrder.selectProductToBuy') }}
            </div>
          </div>
          <div class="item active">
            <div class="number">
              step 02.
            </div>
            <div class="text">
              {{ $t('submitOrder.confirmOrderInformation') }}
            </div>
          </div>
          <div class="item">
            <div class="number">
              step 03.
            </div>
            <div class="text">
              {{ $t('submitOrder.payToCompleteTheOrder') }}
            </div>
          </div>
        </div>
      </div>
      <div class="submit-con">
        <!-- 收货地址 -->
        <div class="submit-box">
          <div class="tit">
            <span class="text">{{ $t('address.receivingAddress') }}</span>
            <!-- <span class="action">显示全部地址</span> -->
          </div>
          <div class="con address-box">
            <div
              v-for="address in addressList"
              :key="address.addrId"
              :class="['item', address.commonAddr?'default-address':'',selectedAddrId===address.addrId?'active':'']"
              @click="changeAddress(address.addrId)"
            >
              <div class="name-phone">
                <span class="name">{{ address.receiver }}</span>
                <span class="phone">{{ address.mobile }}</span>
                <span
                  v-if="!address.commonAddr"
                  class="set-default"
                  @click="setDefaultAddr(address.addrId)"
                >{{ $t('address.setDefault') }}</span>
                <span
                  v-if="address.commonAddr"
                  class="default-tag"
                >{{ $t('address.default') }}</span>
              </div>
              <div
                class="address-detail"
              >
                {{ address.province+address.city+address.area+address.addr }}
              </div>
              <div class="del-edit">
                <span
                  class="edit"
                  @click.stop="editAddr(address.addrId)"
                />
                <span
                  class="del"
                  @click.stop="toggleDelAddr(true,address.addrId)"
                />
              </div>
            </div>
            <div
              class="item add-address"
              @click="toggleAddrPop(true)"
            >
              <div class="add-box">
                <div class="img">
                  +
                </div>
                <div class="text">
                  {{ $t('address.addAddress') }}
                </div>
              </div>
            </div>
          </div>
          <div
            v-if="showDelAddr"
            class="popup-mask"
          />
          <div class="fix-transform-blur">
            <div
              v-if="showDelAddr"
              class="popup-box"
            >
              <div
                class="tit"
                style="padding:10px;"
              >
                <div class="text">
                  {{ $t('tips') }}
                </div>
                <div
                  class="close"
                  @click="toggleDelAddr(false)"
                />
              </div>
              <div class="con">
                <div class="tip">
                  <div class="tip-icon warning" />
                  <div class="tip-info">
                    <div class="result">
                      {{ $t('address.deleteShippingAddress') }}
                    </div>
                    <div class="date">
                      {{ $t('address.deleteShippingTips') }}
                    </div>
                    <div class="btns">
                      <a
                        href="javascrip:void(0);"
                        class="btn-r"
                        @click="delAddr()"
                      >{{ $t('delete') }}</a>
                      <a
                        href="javascrip:void(0);"
                        class="btn-g"
                        @click="toggleDelAddr(flase)"
                      >{{ $t('cancel') }}</a>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 收货地址 -->
        <!-- 支付方式 -->
        <div class="submit-box">
          <div class="tit">
            <span class="text">{{ $t('commonFoot.paymentMethod') }}</span>
          </div>
          <div class="con pay-way">
            <div class="item active">
              {{ $t('submitOrder.payOnline') }}
            </div>
            <!-- <div class="item">货到付款</div>
            <div class="item">线下支付</div>-->
          </div>
        </div>
        <!-- 支付方式 -->
        <!-- 配送方式 -->
        <div class="submit-box">
          <div class="tit">
            <span class="text">{{ $t('submitOrder.deliveryMethod') }}</span>
          </div>
          <div class="con delivery-way">
            <div class="item active">
              {{ $t('submitOrder.courierDelivery') }}
            </div>
            <!-- <div class="item">到店自提</div> -->
            <!-- <div class="description">（该商品不支持自提）</div> -->
          </div>
        </div>
        <!-- /配送方式 -->
        <!-- 商品信息 -->
        <div class="submit-box goods-info">
          <div class="tit">
            <span class="text">{{ $t('applyReturn.productInformation') }}</span>
          </div>
          <div class="goods-msg">
            <div class="msg-tab">
              <div class="img">
&nbsp;
              </div>
              <div class="info">
                {{ $t('products') }}
              </div>
              <div class="unit-price">
                {{ $t('priceOne') }}
              </div>
              <div class="number">
                {{ $t('quantity') }}
              </div>
              <div class="total">
                {{ $t('subtotal') }}
              </div>
            </div>
            <div class="msg-con">
              <!-- 店铺中的商品 -->
              <div class="goods-box">
                <div class="prod-row">
                  <div class="img">
                    <router-link
                      :to="{path:'/detail',query:{prodId:productItemDto.prodId,scoreFee:productItemDto.scorePrice}}"
                      target="_blank"
                      class="img-box"
                    >
                      <ImgShow :src="productItemDto.pic" />
                    </router-link>
                    <div
                      v-if="!(productItemDto.isDelivery)"
                      class="no-delivery"
                    >
                      不支持配送
                    </div>
                  </div>
                  <div class="info">
                    <router-link
                      :to="{path:'/detail',query:{prodId:productItemDto.prodId,scoreFee:productItemDto.scorePrice}}"
                      target="_blank"
                      class="name"
                    >
                      {{ productItemDto.prodName }}
                    </router-link>
                    <span class="sku">{{ productItemDto.skuName }}</span>
                  </div>
                  <div class="unit-price">
                    <span v-if="productItemDto.price > 0">￥{{ parsePrice(productItemDto.price)[0] }}.{{ parsePrice(productItemDto.price)[1] }} +</span> {{ productItemDto.scorePrice/productItemDto.prodCount }}&nbsp;{{ $t('submitOrder.points') }}
                  </div>
                  <div class="number">
                    {{ productItemDto.prodCount }}
                  </div>
                  <div
                    v-if="productItemDto.isDelivery"
                    class="total"
                  >
                    <span v-if="productItemDto.productTotalAmount > 0">￥{{ parsePrice(productItemDto.productTotalAmount)[0] }}.{{ parsePrice(productItemDto.productTotalAmount)[1] }} +</span> {{ productItemDto.scorePrice }}&nbsp;{{ $t('submitOrder.points') }}
                  </div>
                  <div
                    v-else
                    class="total"
                  >
                    ￥0
                  </div>
                </div>
              </div>

              <!-- 留言 -->
              <div
                v-if="productItemDto.isDelivery"
                class="submit-box"
              >
                <div class="remakes">
                  {{ $t('submitOrder.noteMessage') }}：<input
                    v-model="remarks"
                    type="text"
                    maxlength="100"
                    class="text"
                    :placeholder="$t('submitOrder.numberLength100')"
                  >
                </div>
              </div>
              <!-- /留言 -->
            </div>
          </div>
        </div>
        <!-- 商品信息 -->
      </div>
      <div class="submit-bottom">
        <div
          v-if="orderInfo.totalCount"
          class="statistic-box"
        >
          <div class="item">
            <div class="tit">
              <span class="number">{{ orderInfo.totalCount }}</span>{{ $t('submitOrder.totalItems') }}：
            </div>
            <div class="con">
              <span v-if="orderInfo.total > 0">￥{{ parsePrice(orderInfo.total)[0] }}.{{ parsePrice(orderInfo.total)[1] }} +</span> {{ orderInfo.usableScore }}&nbsp;{{ $t('submitOrder.points') }}
            </div>
          </div>
          <div class="item">
            <div class="tit">
              {{ $t('submitOrder.freightPayable') }}：
            </div>
            <div
              class="con"
            >
              ￥{{ parsePrice(transfee)[0] }}.{{
                parsePrice(transfee)[1]
              }}
            </div>
          </div>
          <!-- 平台开启会员包邮(运费减免) -->
          <div
            v-if="orderInfo.freeTransfee"
            class="item"
          >
            <div class="tit">
              {{ $t('submitOrder.memberPackage') }}：
            </div>
            <div class="con bright">
              <p>
                -￥{{ parsePrice(orderInfo.freeTransfee)[0] }}.{{
                  parsePrice(orderInfo.freeTransfee)[1]
                }}
              </p>
            </div>
          </div>
          <div
            v-if="orderInfo.orderReduce"
            class="item"
          >
            <div class="tit">
              {{ $t('submitOrder.offerAmount') }}：
            </div>
            <div
              class="con bright"
            >
              -￥{{ parsePrice(orderInfo.orderReduce)[0] }}.{{ parsePrice(orderInfo.orderReduce)[1] }}
            </div>
          </div>
        </div>

        <div class="detail-box">
          <div class="item">
            <div class="tit">
              {{ $t('submitOrder.totalPayable') }}：
            </div>
            <div class="con">
              <span v-if="orderInfo.actualTotal > 0">￥{{ parsePrice(orderInfo.actualTotal)[0] }}.{{ parsePrice(orderInfo.actualTotal)[1] }} +</span>  {{ orderInfo.usableScore }}&nbsp;{{ $t('submitOrder.points') }}
            </div>
          </div>
          <div
            v-if="currentAddr.addrId"
            class="item"
          >
            <span
              class="text"
            >{{ $t('submitOrder.sendTo') }}：{{ currentAddr.province+' '+currentAddr.city +' '+currentAddr.area+' '+currentAddr.addr }}</span>
            <span class="text">{{ $t('submitOrder.consignee') }}：{{ currentAddr.receiver }} {{ currentAddr.mobile }}</span>
          </div>
        </div>
        <div class="btn-box">
          <a
            v-if="productItemDto.isDelivery"
            href="javascript:void(0)"
            class="btn"
            @click="submitOrder"
          >{{ $t('submitOrder.submitOrder') }}</a>
          <a
            v-else
            href="javascript:void(0)"
            class="disable-btn"
          >{{ $t('submitOrder.submitOrder') }}</a>
        </div>
      </div>
    </div>
    <!-- 地址弹窗 -->
    <AddressPop
      v-if="showAddrPop"
      :edit-addr-id="editAddrId"
      @get-addr-list="getAddrList"
      @reload-order-info="loadOrderInfo"
      @toggle-addr-pop="toggleAddrPop"
    />
    <!-- /地址弹窗 -->
    <confirm-popup
      v-if="dialogVisible"
      :pop-configuration="deliveryConfig"
      @cancel="dialogVisible = false"
      @confirm="$router.go('-1')"
    />
  </div>
</template>

<script setup>
import AddressPop from '@/components/add-or-edit-address/index.vue'
import confirmPopup from '@/components/confirm-popup/index.vue'
import { ElMessage } from 'element-plus'
const router = useRouter()
const route = useRoute()
let orderEntry = 0 // 订单入口 0购物车 1立即购买
onMounted(() => {
  if (route.query.orderEntry) {
    orderEntry = route.query.orderEntry
  }
  uuid = genUUID()
  getAddrList()
  loadOrderInfo()
})

/**
 * 获取地址列表
 */
const addressList = ref([])
const getAddrList = () => {
  http.get('/p/address/list').then(({ data }) => {
    addressList.value = data
  })
}

/**
 * 选择地址
 */
const currentAddr = ref({}) // 当前选择的地址
const selectedAddrId = ref(0)
const changeAddress = (addrId) => {
  addressList.value.forEach(element => {
    if (element.addrId === addrId) {
      currentAddr.value = element
    }
  })
  selectedAddrId.value = addrId
  loadOrderInfo()
}

/**
 * 设置为默认地址
 */
const setDefaultAddr = (addrId) => {
  http.put('/p/address/defaultAddr/' + addrId).then(({ data }) => {
    ElMessage({
      message: data,
      type: 'success',
      duration: 1000
    })
    getAddrList()
  })
}
/**
 * 显示/隐藏确认删除弹窗
 */
const showDelAddr = ref(false)
const editAddrId = ref(0) // 要修改的地址id
const toggleDelAddr = (sts, addrId) => {
  showDelAddr.value = sts
  editAddrId.value = addrId
}
/**
 * 显示/隐藏地址弹窗
 */
const showAddrPop = ref(false) // 地址弹窗显隐
const toggleAddrPop = (sts) => {
  showAddrPop.value = sts
  editAddrId.value = 0
}

/**
 * 修改地址 (弹窗传地址id)
 */
const editAddr = (addrId) => {
  showAddrPop.value = true
  editAddrId.value = addrId
}
/**
 * 删除地址
 */
const delAddr = () => {
  let reload = false
  if (selectedAddrId.value === editAddrId.value) {
    selectedAddrId.value = 0
    reload = true
  }
  http.delete('/p/address/deleteAddr/' + editAddrId.value).then(({ data }) => {
    ElMessage({
      message: data,
      type: 'success',
      duration: 1000
    })
    toggleDelAddr(false)
    getAddrList()
    if (reload) {
      loadOrderInfo()
    }
  })
}
/**
 * 价格处理
 */
const parsePrice = (value) => {
  let val = Number(value)
  if (!val) {
    val = 0
  }
  // 截取小数点后两位，并以小数点为切割点将val转化为数组
  return val.toFixed(2).split('.')
}

/**
 * 加载订单数据
 */
let uuid = ''
const transfee = ref(0) // 应付运费
const orderInfo = ref({})
const productItemDto = ref([])
const loadOrderInfo = () => {
  const orderParam = {
    addrId: selectedAddrId.value,
    dvyType: 1,
    orderItem: orderEntry === '1' ? JSON.parse(sessionStorage.getItem('bbcOrderItem')) : undefined,
    basketIds: orderEntry === '0' ? JSON.parse(sessionStorage.getItem('bbcBasketIds')) : undefined,
    userChangeCoupon: 1,
    uuid
  }
  http.post('/p/score/confirm', orderParam).then(({ data }) => {
    orderInfo.value = data

    // 判断商品是否支持当前地址
    if (data.shopCartOrders && data.shopCartOrders.length > 0) {
      productItemDto.value = data.shopCartOrders[0].shopCartItemDiscounts[0].shopCartItems[0]
    } else {
      productItemDto.value = data.filterShopItems[0]
    }
    if (data.userAddr) {
      currentAddr.value = data.userAddr
      selectedAddrId.value = data.userAddr.addrId
    }
    if (data.totalTransFee && data.freeTransFee) {
      transfee.value = accuracyCount(data.totalTransFee, data.freeTransfee, 1)
    } else {
      transfee.value = data.totalTransFee
    }
  }).catch(() => { })
}

/**
 * 提交订单
 */
const dialogVisible = ref(false)
const deliveryConfig = ref({
  title: '提示',
  firstLineText: '',
  confirmText: '确认',
  cancelText: '取消'
})
const remarks = ref('') // 留言
const languageStore = useLanguageStore()
const submitOrder = () => {
  if (!addressList.value.length) {
    ElMessage({
      message: $t('submitOrder.pleaseAddTheAddressFirst'),
      type: 'warning',
      duration: 1000
    })
    showAddrPop.value = true
    return
  }
  if (selectedAddrId.value === 0) {
    ElMessage({
      message: $t('submitOrder.pleaseAddTheAddressFirst'),
      type: 'warning',
      duration: 1000
    })
    document.body.scrollTop = document.documentElement.scrollTop = 0
    return
  }
  const orderFlowLogParam = JSON.parse(localStorage.getItem('bbcFlowAnalysisLogDto')) || {}
  let step = localStorage.getItem('bbcStep') * 1
  step += 1
  orderFlowLogParam.visitType = 1
  orderFlowLogParam.step = step
  http.post('/p/order/submit', {
    orderShopParams: [{
      remarks: remarks.value,
      shopId: productItemDto.value.shopId
    }],
    uuid,
    orderFlowLogParam
  }).then(({ data }) => {
    // 请求成功后，更新缓存
    localStorage.setItem('bbcStep', step)
    localStorage.setItem('bbcFlowAnalysisLogDto', JSON.stringify(orderFlowLogParam))
    localStorage.setItem('bbcSessionTimeStamp', new Date().getTime()) // 更新会话时间
    if (data.duplicateError === 1) {
      languageStore.handleChangeErrMsg($t('submitOrder.duplicateErrorTips'))
      return ElMessage.warning($t('submitOrder.duplicateErrorTips'))
    }
    sessionStorage.setItem('bbcPay_total', orderInfo.value.actualTotal)
    sessionStorage.setItem('bbcPay_orderNumber', data.orderNumbers)
    router.push({
      path: '/payment'
    })
  }).catch(({ data }) => {
    if (data.code === 'A07001') {
      deliveryConfig.value.firstLineText = data.msg + productItemDto.value.prodName
      dialogVisible.value = true
    }
  })
}

/**
 * 生成uuid
 */
const genUUID = () => {
  const s = []
  const hexDigits = '0123456789abcdef'
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-'

  return s.join('')
}

</script>

<style lang="scss" scoped>
@use '../submit-order/index.scss';
.fix-transform-blur {
  z-index: 10000;
  position: fixed;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -40%);
}
.page-submit-order {
 .submit-box {
    padding-left: 20px;
    .goods-msg {
      .msg-con {
        background: #f9f9f9;
        margin-top: 0;
        padding-bottom: 30px;
        border-bottom: 1px solid #eee;
        .goods-box {
          margin: 0 15px;
          &::after {
            left: 0;
            right: 0;
          }
        }
        .img {
          padding: 0 15px 0 0;
        }
      }
      .msg-tab {
        .img {
          padding: 0 15px 0 0;
        }
      }
    }
    .remakes {
      margin-top: 15px;
      .text {
        margin-left: 0;
      }
    }
  }
  .statistic-box {
    .item {
      .con {
        min-width: 120px;
        width: auto;
      }
      min-height: 33px;
      line-height: 33px;
    }
  }
  .detail-box {
    .item {
      .con {
        min-width: 120px;
        width: auto;
      }
    }
  }
}

</style>
